package com.wntms.config;


import com.wntms.auser.exceptions.AuthenticationEntryPointImpl;
import com.wntms.config.filter.LoginFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//开启授权
@EnableGlobalMethodSecurity(prePostEnabled=true)
@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private LoginFilter loginFilter;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //配置一些东西

        //禁止跨域请求伪造
        http.csrf().disable()
                //不用session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().authorizeRequests()
                //login需要认证
                .antMatchers("/**/login").anonymous()
                //其他请求需要认证
                .anyRequest().authenticated();

        //设置过滤器的先后顺序
        http.addFilterBefore(loginFilter, UsernamePasswordAuthenticationFilter.class);

        //配置统一异常处理
        http.exceptionHandling()
                //配置认证异常
                .authenticationEntryPoint(new AuthenticationEntryPointImpl())
                //配置授权异常
                .accessDeniedHandler(new AccessDeniedHandlerImpl());

        //配置跨域
        http.cors();
    }
}
